package com.jf3q.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jf3q.admin.dto.CourseDto;
import com.jf3q.admin.service.EduCourseDescriptionService;
import com.jf3q.admin.service.EduCourseService;
import com.jf3q.admin.service.EduSubjectService;
import com.jf3q.admin.service.EduTeacherService;
import com.jf3q.common.domain.EduCourse;
import com.jf3q.common.domain.EduCourseDescription;
import com.jf3q.common.domain.EduSubject;
import com.jf3q.common.domain.EduTeacher;
import com.jf3q.common.exception.JfException;
import com.jf3q.common.utils.OssUtils;
import com.jf3q.common.vo.ResultVo;
import com.jf3q.common.vo.CourseInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.security.auth.Subject;
import java.util.List;


/**
 * @author:xiaojie
 * @create: 2023-05-03 15:06
 * @Description:
 */
@RestController
@RequestMapping("/course")
@Tag(name = "课程模块")
public class CourseController {

    @Autowired
    RedisTemplate redisTemplate;
    @Value("${redis.newCoursesKey}")
    String newCoursesKey;

    @Autowired
    EduCourseService eduCourseService;
    @Autowired
    EduTeacherService teacherService;
    @Autowired
    EduSubjectService subjectService;
    @Autowired
    EduCourseDescriptionService courseDescriptionService;
    //    @PreAuthorize("hasAuthority('course:list')")
    @Operation(summary = "查看课程列表")
    @PostMapping("/getPage/{pageCount}")
    public ResultVo getPage(@RequestBody CourseDto courseDto, @PathVariable Integer pageCount){
        LambdaQueryWrapper<EduCourse> queryWrapper=new LambdaQueryWrapper<>();
        if (ObjectUtils.isNotEmpty(courseDto)) {
            if (StringUtils.isNotEmpty(courseDto.getTitle())) {
                queryWrapper.like(EduCourse::getTitle, courseDto.getTitle());
            }
            if (StringUtils.isNotEmpty(courseDto.getStatus())) {
                queryWrapper.eq(EduCourse::getStatus, courseDto.getStatus());
            }
        }
        Page<EduCourse> page = eduCourseService.page(new Page<>(courseDto.getPageNow(), pageCount), queryWrapper);
        return ResultVo.success("",page);
    }

    @Autowired
    OssUtils ossUtils;

    @PostMapping("/uploadCover")
    public ResultVo uploadCover(MultipartFile file){
        return ResultVo.success("上传成功",ossUtils.upload("course",file));

    }

    @Operation(summary = "获取讲师下拉列表")
    @GetMapping("/getTeacher")
    public ResultVo getTeacher(){
        List<EduTeacher> list = teacherService.list();
        return ResultVo.success("",list);
    }
    @Operation(summary = "添加/修改课程基本信息")
    @PostMapping("/saveOrupdate")
    public ResultVo saveCourse(@RequestBody CourseInfoVo courseInfoVo){
        //1 向课程表添加课程基本信息
        //CourseInfoVo对象转换eduCourse对象
        EduCourse eduCourse = new EduCourse();
        BeanUtils.copyProperties(courseInfoVo,eduCourse);
        boolean flag = eduCourseService.saveOrUpdate(eduCourse);

        if(flag == false) {
            //添加失败
            throw new JfException(20001,"添加课程信息失败");
        }

        //获取添加之后课程id
        String cid = eduCourse.getId();

        //2 向课程简介表添加课程简介
        //edu_course_description
        EduCourseDescription courseDescription = new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        //设置描述id就是课程id
        courseDescription.setId(cid);
        courseDescriptionService.saveOrUpdate(courseDescription);

        if(StringUtils.checkValNotNull(courseInfoVo.getId())){
            //发布完也可能修改课程基本信息

            Long index = indexOfNewCourses(courseInfoVo.getId());
            if (index!=-1L) {
                redisTemplate.opsForList().set(newCoursesKey,index , eduCourse);

            }

        }




        return ResultVo.success("添加成功",cid);
    }

    @Operation(summary = "删除课程")
    @DeleteMapping("{id}")
    public ResultVo del(@PathVariable String id){
        eduCourseService.del(id);
        //如果没出现异常就把redis里的也删掉

        Long index = indexOfNewCourses(id);
        if (index!=-1L) {
            Object removedElement = redisTemplate.opsForList().index(newCoursesKey, index);
            if (removedElement != null) {
                redisTemplate.opsForList().remove(newCoursesKey,1,removedElement);

                //有个小瑕疵：后面的没顶进来（可以把一开始的存的redis的那个范围设置大一点，比如我要最新的3篇，那咱设置list大小为6，基本够用）
            }
        }


        return ResultVo.success("删除成功",null);
    }

    @Operation(summary = "获取一级课程分类列表")
    @GetMapping("/getLevel1")
    public ResultVo getSubject(){
        LambdaQueryWrapper<EduSubject> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getParentId,"0");
        List<EduSubject> subjectList = subjectService.list(queryWrapper);
        return ResultVo.success("",subjectList);
    }

    @Operation(summary = "获取二级课程分类列表")
    @GetMapping("/getLevel2/{sId}")
    public ResultVo getLevel2(@PathVariable String sId){
        LambdaQueryWrapper<EduSubject> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduSubject::getParentId,sId);
        List<EduSubject> subjectList = subjectService.list(queryWrapper);
        return ResultVo.success("",subjectList);
    }
    @Operation(summary = "课程详细信息查看")
    @PostMapping("/showOne/{cId}")
    @Transactional
    public ResultVo showCourse(@PathVariable String cId){
        EduCourse byId = eduCourseService.getById(cId);
        EduCourseDescription courseDescription = courseDescriptionService.getById(cId);
        byId.setDescription(courseDescription.getDescription());
        return ResultVo.success("", byId);
    }

    @Operation(summary = "封面信息")
    @PostMapping("/showOver/{cId}")
    public ResultVo showOver(@PathVariable String cId){
        EduCourse course=eduCourseService.getOver(cId);
        return ResultVo.success("",course);
    }
    private Long indexOfNewCourses(String courseId) {
        // 获取课程列表
        List<EduCourse> courses = redisTemplate.opsForList().range(newCoursesKey, 0, -1);

        // 找到文章的索引
        for (int i = 0; i < courses.size(); i++) {
            if (courses.get(i).getId().equals(courseId)) {
                return Long.valueOf(i);
            }
        }
        return -1L; // 课程不在列表中
    }

    @Operation(summary = "确认发布")
    @PostMapping("/status/{cId}")
    public ResultVo status(@PathVariable String cId){
        EduCourse course = eduCourseService.getById(cId);
        if(!course.getStatus().equals("Normal")){
            redisTemplate.opsForList().leftPush(newCoursesKey,course );
            // 获取当前列表的长度
            long listSize = redisTemplate.opsForList().size(newCoursesKey);

            // 如果列表长度超过3，截断列表，保留最新的3个元素
            if (listSize > 3) {
                redisTemplate.opsForList().trim(newCoursesKey, 0, 2);
            }
        }
        course.setStatus("Normal");
        eduCourseService.updateById(course);
        return ResultVo.success("",null);
    }


}
